package pagesearch

import (
	"fmt"
	"time"

	"gioui.org/io/key"
	"gioui.org/layout"
	"gioui.org/widget/material"
	"git.sr.ht/~mil/transito/connhttp"
)

func wgButtonSearch(widget *PageSearch, gtx layout.Context) layout.Dimensions {
	if widget.clickableSearch.Clicked() {
		key.SoftKeyboardOp{Show: false}.Add(gtx.Ops)
		go func() {
			now := time.Now()
			widget.TimerStartNominatim = &now
			defer func() {
				widget.TimerStartNominatim = nil
				widget.UIState.Window.Invalidate()
			}()

			if result, err := connhttp.FetchNominatim(
				widget.textfieldSearch.Text(),
				widget.UIState.Sources,
			); err != nil {
				widget.selectListItems = []string{
					fmt.Sprintf("Nominatim Fetch error: %v", err),
				}
			} else {
				widget.selectListItems = []string{}
				for _, item := range *result {
					widget.selectListItems = append(widget.selectListItems, fmt.Sprintf(
						"%s - Latlon: %s %s",
						item.DisplayName, item.Lat, item.Lon,
					))
				}
			}
		}()
	}
	return material.Button(widget.UIState.Theme, &widget.clickableSearch, "Search").Layout(gtx)
}
